/**
 * Class to help with signing of documents
 */
package us.gaaoc.framework.signature.digital;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.cert.CertPath;
import java.security.cert.CertificateException;
import java.security.cert.CertificateExpiredException;
import java.security.cert.CertificateNotYetValidException;
import java.security.cert.CertificateParsingException;
import java.security.cert.X509Certificate;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.apache.log4j.Logger;

import us.gaaoc.framework.dao.ModelFacade;
import us.gaaoc.framework.dao.ModelFacadeHibernate;
import us.gaaoc.framework.model.CounterPerSigner;
import us.gaaoc.framework.model.DocumentStatus;
import us.gaaoc.framework.model.Documents;
import us.gaaoc.framework.model.LdapDirectoryPerson;
import us.gaaoc.framework.model.Person;
import us.gaaoc.framework.model.Roles;
import us.gaaoc.framework.model.Signatures;
import us.gaaoc.framework.util.DateUtil;

/**
 * Class to help with signing of documents
 * @author mcelratr
 * 
 */
@SuppressWarnings("unchecked")
public class DigitalSignerController {

	//the following booleans were added for rendering and navigating purposes 
	//in case the signature function fails
	private boolean renderRejectButton = false;
	private boolean docNoContentsMessage = false;
	private boolean signatureFailed = false;
	private boolean signatureFailedMessage = false;
	private CounterPerSigner signatureCounterPerSigner;
	private String signatureTrackingID;
	private boolean signedDoc;
	private boolean orderedDoc;


	private static transient Logger LOG = Logger.getLogger(DigitalSignerController.class);
	private static transient Logger Sign = Logger.getLogger("SignedFailed");

	/**
	 * @return the signedDoc
	 */
	public boolean isSignedDoc() {
		return signedDoc;
	}
	/**
	 * @param signedDoc the signedDoc to set
	 */
	public void setSignedDoc(boolean signedDoc) {
		this.signedDoc = signedDoc;
	}
	/**
	 * @return the orderedDoc
	 */
	public boolean isOrderedDoc() {
		return orderedDoc;
	}
	/**
	 * @param orderedDoc the orderedDoc to set
	 */
	public void setOrderedDoc(boolean orderedDoc) {
		this.orderedDoc = orderedDoc;
	}
	/**
	 * This method gets called when user presses the sign button to sign
	 * PDF or XML document
	 * @param roleUuid 
	 * @param ldPerson 
	 * @return String
	 * @throws Exception 
	 * @throws IOException 
	 * @throws Exception
	 */
	public byte[] signDocument(Documents docToSignPassedIn, Person personSignerPassedIn, String roleUuid) throws Exception {
		//String returnString = "stay";
		
		Documents docToSign = docToSignPassedIn;
		Person personSigner = personSignerPassedIn;
		//List <Roles > roleList = personSigner.getRoles();
		boolean isDocSigned =false;
		byte[] sigInByte = docToSignPassedIn.getContent();
		
		//String testRoleUuid = "";
		String clerkRoleUuid = "uuid2"; // The Clerk Role UUID
		String judgeRoleUuid = "uuid4"; // The Judge Role UUID
		String attorneyRoleUuid = "uuid6"; // The Attorney Role UUID
		String agentRoleUuid = "uuid5"; // The Agent Role UUID

//		for (Roles r : roleList) {
//			// Is the role that of clerk and if a signature is present
//			testRoleUuid = r.getUuid().toString();			
			if (roleUuid.equals(clerkRoleUuid)) {
				//isDocSigned = isDocumentSignedForClerk(docToSign,personSigner);
				isDocSigned = true;
			} else if(roleUuid.equals(judgeRoleUuid)) {
				isDocSigned = isDocumentSignedForJudge(docToSign,personSigner);
			} else if(roleUuid.equals(attorneyRoleUuid)) {
				//for Testing
				//isDocSigned = isDocumentSignedForAttorney(docToSign,personSigner);
				isDocSigned = true;
			}else if(roleUuid.equals(agentRoleUuid)) {
				isDocSigned = isDocumentSignedByAgent(docToSign,personSigner);
			}
//		}

		// Sign the document
		if (!isDocSigned) {
			
			if(docToSign.getContent() != null){
				LOG.debug("Document "+docToSign.getTitle() + "has been signed");               //Added Code brownb
				 //For Testing
				//sigInByte = signPDFDocument(docToSign, personSigner,roleUuid,ldPerson);
				sigInByte = docToSign.getContent();

			}
		}
		if(sigInByte == null) {
			
			sigInByte = docToSign.getContent();
		}
		
		LOG.debug("Verify again that the documents is signed.."+ docToSign.isSignedDoc());
		return sigInByte;
	}
	
	
	
	/*
	 * This method is get called after the court received stamping is done on the documents.
	 * So we don't need to check for the document is order or not
	 * PDF or XML document
	 * @param roleUuid 
	 * @param ldPerson 
	 * @return String
	 * @throws Exception 
	 * @throws IOException 
	 * @throws Exception
	 *
	public byte[] signDocumentAfterCourtStamping(Documents docToSignPassedIn, 
			Person personSignerPassedIn, String roleUuid, LdapDirectoryPerson ldPerson) throws Exception {
		
		byte[] sigInByte = docToSignPassedIn.getContent();
		Documents docToSign = docToSignPassedIn;
		Person personSigner = personSignerPassedIn;
		//if(docToSign.getDocumentInstance().getCode() != 181) {		//Sheriff's Entry of Service - Filed - Bibb
			sigInByte = signPDFDocument(docToSign, personSigner,roleUuid,ldPerson);
			if(sigInByte == null) {
				sigInByte = docToSign.getContent();
				this.setSignedDoc(false);
			}
		//}
			this.setSignedDoc(true);
			LOG.debug("Verify again that the documents is signed.."+ docToSign.isSignedDoc());
			return sigInByte;
	}
	*/
	/**
	 * This method signs the PDF documents. After signing updates the GAJE
	 * database.
	 * 
	 * @param doc The document to sign
	 * @param roleUuid 
	 * @param ldPerson 
	 * @throws IOException 
	 * @throws CertificateException 
	 * @throws IOException 
	 * @throws Exception
	 */
	public byte[] signPDFDocument(Documents doc, Person personSignerPassedIn, String roleUuid, LdapDirectoryPerson ldPerson) throws Exception {
		/*
		 * Note: Allow signing only of designated documents such as orders/warrants.
		 */

		/*
		 * Set up for Processing Section
		 */
		LOG.debug("Inside the signPDFDocument method of the case details page");
		byte[] docContent = doc.getContent();
		if (docContent.length == 0) {
			LOG.warn("The pdf file has no contents ");
			LOG.error("Problem Signing");
			doc.setSignedDoc(false);
			return docContent;
		}
		String cnName = ldPerson.getCname();
		String password = ldPerson.getCertPassword();
		
		docContent = doc.getContent();
		ByteArrayInputStream document = new ByteArrayInputStream(docContent);	
		/*
		 * Create a digital signature of the document
		 * If the digital signature function fails set 
		 * the stautus of the passed in document as failed signature 
		 * of the user and return
		 * The status of the case record remains the same if the signature fails
		 * for example if the user is the attorney then the status of the case record
		 * is still SentToAttorney or if the user is the clerk then 
		 * the case record status is Received
		 */
		
		DigitalSigner pdfSigner = new DigitalSigner();
		byte[] sigInByte = pdfSigner.sign(document, cnName, password);	
		if(sigInByte ==  null) {
			this.setSignedDoc(false);
			this.setOrderedDoc(false);
	
		}
		else {
			this.setSignedDoc(true);
			this.setOrderedDoc(false);
		}		
		return sigInByte;
	}
	
	/**
	 * This method updates the database after visual signature and physical signatures are done.
	 * @param doc
	 * @param ds
	 * @param person
	 * @param sigInByte
	 * @throws CertificateException
	 * @throws IOException
	 */
	public void updateDatabaseAfterSigned(Documents doc,DocumentStatus ds,
			Person person,byte[] sigInByte) 
		throws CertificateException, IOException {
	
		// Get X509 Certificate
		X509Certificate x509Certificate = this.getX509Certificate(SignatureAndCertChain.certificationChain);
		
		// Set document type variable
		String doctype = doc.getDocumentInstance().getCode()+"";	
		byte [] docContent = doc.getContent();
		
		this.getModelFacade().updateDocumentStatus(doc.getUuid(), ds);
		
		// Signature counter section for signature tracking ID's
		boolean isSigner = this.getModelFacade().isSigner(person.getUuid());

		// check if the signer is in the table counterPerSigner
		if (!isSigner) {
			LOG.info("if signer is not in counterPerSigner table create signer ");
			this.createCounterPerSigner(person);
		}
		
		this.updateCounterPerSigner(person,doctype);
		
		// Insert the signature value and the corresponding fields in the
		// Signature Table.
		this.createSignature(person, doc,sigInByte,x509Certificate);
		
		//Readded to resolve issue:
		//	b7006e6c-695c-11dd-945f-00301b45ff56
		//commit the transaction
		//HibernatePhaseListener.getSessionFactory().getCurrentSession().getTransaction().commit();
		//------------------

		// Validate the Signature
		SignatureValidator sigVal = new SignatureValidator();
		sigVal.validate(docContent, sigInByte,SignatureAndCertChain.certificationChain);
		this.verifyCertForExpirationDate(x509Certificate, DateUtil.getCurrentDate());
		LOG.info("Expiration Date of certificate is verified");		
	}
	
	private void createSignature(Person person,Documents doc, byte[] sigInByte, X509Certificate x509Certificate) throws CertificateException, IOException {
		LOG.info("Creating a signatures object and persisting it...");
		
		Date certExpirationDate = (x509Certificate.getNotAfter());
		
		Signatures sig = new Signatures();
		sig.setSignatureValue(sigInByte);
		sig.setCertificateChain(SignatureAndCertChain.certificationChain);
		sig.setCreationDate(DateUtil.getCurrentDate());
		sig.setExpirationDate(DateUtil.utilToSqlDate(certExpirationDate));
		sig.setSignedByPerson(person);
		sig.setDocument(doc);
		sig.setX509Certificate(x509Certificate);
		sig.setIssuerName(x509Certificate.getIssuerDN().getName());
		sig.setIssuerNumber(x509Certificate.getSerialNumber());
		sig.setDigestValue(null);
		sig.setSignatureTrackingId(this.getSignatureTrackingID());
		this.getModelFacade().makePersistent(sig);
		LOG.info("Signature has been persisted...");
	}
	
	private void updateCounterPerSigner(Person person,String doctype) {
		
		signatureCounterPerSigner = this.getModelFacade().findCounterPerSignerBySignerUuid(person.getUuid());
	
		DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
		String formattedDate = stripOfAllSlashes(dateFormat.format(DateUtil.getCurrentDate())).toString();
		int counterValue = this.signatureCounterPerSigner.getCounterValue();
			
		this.setSignatureTrackingID(formattedDate+ person.getUserId()
				+ counterValue + stripOfAllNonAlfaNumeric(doctype));

		this.getModelFacade().updateCounterPerSigner(person.getUuid());

	}
	private void createCounterPerSigner(Person person) {
		CounterPerSigner counterForThisSigner = new CounterPerSigner();
		// Create UUID for signature record
		UUID uuid = UUID.randomUUID();
		counterForThisSigner.setCounterUuid(uuid.toString());
		counterForThisSigner.setCounterValue(1);
		counterForThisSigner.setDateOfLastSignature(DateUtil.getCurrentDate());
		counterForThisSigner.setPersonUuid(person.getUuid());
		this.getModelFacade().insertCounterPerSigner(counterForThisSigner);
	}
	
	/**
	 * This method should not have side affects!
	 
	public boolean isDocumentSignedForClerk(Documents doc,Person person) {
		boolean documentSigned = false;
		// Has another clerk signed the document
	//	boolean anotherClerkSignedFlag = false;
		boolean ordered = this.isDocumentOrderForClerk(doc);

		List <Signatures>docSignatures = doc.getSignatures();
		// Is it a document to sign . . .
		if(ordered) {
			// Loop through the signatures  in the docSignatures list
			for(Signatures s : docSignatures) {
				// Get the person signed
				Person personSigned = s.getSignedByPerson();
				// Find the role of the person, see if a clerk
				List<Roles> signerRoles = personSigned.getRoles();
				for (Roles r : signerRoles) {
					// Is the role that of clerk and if a signature is present
					String testRoleUuid = r.getUuid().toString();
					String targetRoleUuid = "uuid2"; // The Clerk Role UUID
					if (testRoleUuid.equals(targetRoleUuid)) {
						if(s.getSignatureValue() != null) {
							anotherClerkSignedFlag = true;
						}	
					}
				}
				LOG.debug("Signed Person Uuid "+personSigned.getUuid());
				LOG.debug("Parameter passes Person Uuid "+person.getUuid());
				// If this person is the person that has signed the document ...
				// or another clerk has already signed the document ...
				if(personSigned.getUuid().equals(person.getUuid()) || anotherClerkSignedFlag) {
					// and the signature value isn't null
					if(s.getSignatureValue() != null) {
						// Set the flags to show that the document has been signed and
						// doesn't need to be signed again.
						documentSigned = true;
						//doc.setSignedDoc(true);
						//doc.setOrderedDoc(false);
						break;
					}
				} 
				//break;
			}
		}else if ((ordered) && (doc.getStatus().getCode() == 2)) {
			documentSigned = true;
			//doc.setSignedDoc(true);
		}
		return documentSigned;
	}
	*/
	
	public boolean isDocumentSignedForClerk(Documents doc,Person person) {
		

		boolean documentSigned = false;
		boolean ordered = this.isDocumentOrderForClerk(doc);

		if ((ordered) && (doc.getStatus().getCode() != 2) && (doc.getStatus().getCode() != 8)) {
			documentSigned = true;
		}
		return documentSigned;
	
		
		
		
	}


	private X509Certificate getX509Certificate(byte[] certificationChain) throws IOException, CertificateException {
		X509Certificate cert =null;
		SignatureValidator validator = new SignatureValidator();
		InputStream in = new ByteArrayInputStream(certificationChain);

		// Read the certificate file and save it into the string
		String certChainBase64Encoded = null;
		BufferedReader br  = new BufferedReader(new InputStreamReader(in));
		certChainBase64Encoded = br.readLine();

		CertPath certPath = validator.loadCertPathFromBase64String(certChainBase64Encoded);
		List certsInChain = certPath.getCertificates();
		X509Certificate[] X509CertificateChain = (X509Certificate[])certsInChain.toArray(new X509Certificate[0]);
		cert = X509CertificateChain[0];

		return cert;
	}

	public void verifyCertForExpirationDate(X509Certificate cert, Date date) throws CertificateExpiredException, CertificateNotYetValidException, CertificateParsingException {
		/*
		String issuerName = cert.getIssuerDN().getName();
		LOG.debug("Issuer DN :" +issuerName);
		String subjectName = cert.getSubjectDN().getName();
		LOG.debug("Subject DN : "+subjectName);
		String issuerX500Principal = cert.getIssuerX500Principal().getName();
		LOG.debug("Issuer Principal :"+issuerX500Principal);
		LOG.debug("Serial Number :"+ cert.getSerialNumber());

		//Iterator iter = x509IssuerSerialList.iterator();
		/*List<List<X>> x509IssuerSerialList = (List<List<X509IssuerSerialType>>) cert.getIssuerAlternativeNames ();
		int size = x509IssuerSerialList.get(0).size();
		for(int i=0; i<size; i++) {
			String name = x509IssuerSerialList.get(0).get(i).getX509IssuerName();
			LOG.debug("Issuer Serial Alternative Name :"+name);
		}*/


		cert.checkValidity(date);

	}

//	TODO May not need this method in this class
//	Comment: THis is the digital controller class so all the document to sign should get tested 
//	in this class 
	/**
	 * Helper method to check the document is a type of "Order" or "Warrant" from the 
	 * given document code and whether document requires clerk's signature
	 * 
	 * This method should not have side affects!
	 * 
	 * @return boolean
	 */
	public boolean isDocumentOrderForClerk(Documents doc) {
		String docCode = doc.getDocumentInstance().getDocLocalCode().getCode();
		boolean documentOrder = false;
		
		int docType = doc.getDocumentInstance().getDocumentType().getCode();
		int docInstance = doc.getDocumentInstance().getCode();
		/*
		 * to replace hard coding with database verification
		 */
		if((docType == 34) || (docInstance == 729) ||  //Fulton's document of Complaint
				(docType == 27 && docInstance != 610)){ //rule nisi for douglas is not signed by clerk
			/*
	//all these docCodes are checking for the orders and docStatus =6 is 
	//for document signed.
	if((docCode.equals("124320") ||docCode.equals("124321")||
			docCode.equals("124680")||docCode.equals("124650")||
			docCode.equals("126250")||docCode.equals("124300")||
			docCode.equals("125110")||docCode.equals("125210")||
	//		docCode.equals("129350"))  {
    //   For Summons and Rule Nisi, later on for Bibb County it should be 129315
			docCode.equals("129310")) ||(docCode.equals("129315"))){
			System.out.print("The document code is " + docCode);*/
			LOG.info("The document code is " + docCode);
			documentOrder = true;
			//doc.setOrderedDoc(true);				
		}
		else {
			documentOrder = false;
			//doc.setOrderedDoc(false);
		}
		
		if(documentOrder == false) {
			documentOrder = doc.getDocumentInstance().isRequiresClerkSignature();
		}
		
		return documentOrder;
	}

	public String getSignatureTrackingID() {
		return signatureTrackingID;
	}

	public void setSignatureTrackingID(String signatureTrackingID) {
		this.signatureTrackingID = signatureTrackingID;
	}

	private String stripOfAllSlashes(String string){
		String slash = "/";
		if(string.indexOf(slash)!=-1){
			string = string.substring(0, string.indexOf(slash))+string.substring(string.indexOf(slash)+1);
			if(string.indexOf(slash)!=-1){
				string = string.substring(0, string.indexOf(slash))+string.substring(string.indexOf(slash)+1);
				return string;
			}else{
				return string;
			}
		}else{
			return string;
		}
	}
	private String stripOfAllNonAlfaNumeric(String string){
		String space = " ";
		char spChar = space.charAt(0);
		char colonChar = ":".charAt(0);
		char singleQ = "\'".charAt(0);
		string = removeChar(string, spChar);
		string = removeChar(string, colonChar);
		string = removeChar(string, singleQ);

		return string;
	}

	private String removeChar(String s, char c) {
		String r = "";
		for (int i = 0; i < s.length(); i ++) {
			if (s.charAt(i) != c) r += s.charAt(i);
		}
		return r;
	}
	/**
	 * @return Returns the modelFacade.
	 */
	protected ModelFacade getModelFacade() {
		return ModelFacadeHibernate.getInstance();
	}

	/**
	 * Helper method to check the document is a type of "Order" or "Warrant"
	 * from the given document code and whether document requires attorney signature
	 * 
	 * @return boolean
	 */
	public boolean isDocumentOrderForAttorney(Documents doc) {

		boolean documentOrder = false;

		/*
		 * For document category = "Request","Complaint", "Petition", and
		 * "Motion"
		 */

		
		int docCategoryCode = doc.getDocumentInstance().getDocumentType()
		.getDocumentCategory().getCode();
		int docTypeCode = doc.getDocumentInstance().getDocumentType().getCode();
		int docInstanceCode = doc.getDocumentInstance().getCode();
		
		if ((docCategoryCode == 9)			//Request
				|| (docCategoryCode == 6)	//Complaint
				|| (docCategoryCode == 10)	//Motion
				|| (docCategoryCode == 13)	//Petition
				|| (docTypeCode == 19)  // Notice to Produce
				|| (docTypeCode == 43) // Notice of Registration
				|| (docTypeCode == 24) // Income Deduction Order
				|| (docTypeCode == 26) // Rule Absolute Order
				|| (docTypeCode == 23) // Final Order
				|| (docTypeCode == 28) // Support Order
				|| (docTypeCode == 22) // Contempt Order
				|| (docInstanceCode == 604) // Voluntary Dismissal
				|| (docTypeCode == 50) // Deduction Order
				|| (docInstanceCode == 720) //Notice of Final Hearing
//				|| (docInstanceCode == 728) //Certificate of Service
				|| (docInstanceCode == 729) //Complaint for Recovery of Child Support
				|| (docInstanceCode == 25002) // CERTIFICATION UNDER RULE 3.2
				|| (docInstanceCode == 25009) // VOLUNTARY DISMISSAL
			) {  
			documentOrder = true;
			//doc.setOrderedDoc(true);
		} else {
			documentOrder = false;
			//doc.setOrderedDoc(false);
		} 
		if (docInstanceCode == 754 || docInstanceCode == 746 || docInstanceCode == 730 || docInstanceCode == 739 
				|| docInstanceCode == 747 || docInstanceCode == 748 || docInstanceCode == 749 || docInstanceCode == 750
				|| docInstanceCode == 751 || docInstanceCode == 752 || docInstanceCode == 753 || docInstanceCode == 756) {
			documentOrder = false; //Fulton's Special Order
		}
		
		if(documentOrder == false)	{
			documentOrder = doc.getDocumentInstance().isRequiresAttorneySignature();
		}
		
		return documentOrder;
	}


	public boolean isDocumentSignedForAttorney(Documents doc, Person person) {
		boolean documentSigned = false;
		boolean ordered = this.isDocumentOrderForAttorney(doc);

		//List<Signatures> docSignatures = new ArrayList<Signatures>();
		//docSignatures = doc.getSignatures();
		if ((ordered) && (doc.getStatus().getCode() != 2)) {
			
			documentSigned = true;
/*
			for (Signatures s : docSignatures) {
				Person personSigned = s.getSignedByPerson();
				LOG.debug("Signed Person Uuid "
						+ personSigned.getUuid());
				LOG.debug("Parameter passes Person Uuid "
						+ person.getUuid());
				if (personSigned.getUuid().equals(person.getUuid())) {
					if (s.getSignatureValue() != null) {
						documentSigned = true;
						break;
					}
				}				
			}
			
		}
		*/
		}
		/*
		 else if ((ordered) && (doc.getStatus().getCode() == 2)) {
			documentSigned = true;
			//doc.setSignedDoc(true);
		}*/

		return documentSigned;
	}

	public boolean isDocumentOrderForJudge(Documents doc) {		
		int docInstanceCode = doc.getDocumentInstance().getCode();
		boolean documentOrder = false;
		if (docInstanceCode == 57			//Order:Adding Party
				|| docInstanceCode == 59		//Order:Contempt Amended
				|| docInstanceCode == 61		//Order:Contempt Order with Concurrent Jurisdiction
				|| docInstanceCode == 63		//Order:Child Support Enforcement Order For Release on Contempt
				|| docInstanceCode == 65		//Order: Final
				|| docInstanceCode == 67		//Order: Final for Medical Support
				|| docInstanceCode == 69		//Order: Income Deduction
				|| docInstanceCode == 71		//Order: Paternity Testing
				|| docInstanceCode == 73		//Order: Rule Absolute
				|| docInstanceCode == 75		//Order: Rule Nisi
				|| docInstanceCode == 77		//Order: Support
				|| docInstanceCode == 79		//Order: Temporary
				|| docInstanceCode == 81		//Order: To Correct Clerical Error
				|| docInstanceCode == 83		//Order: Transfer
				|| docInstanceCode == 85		//Order: Review-Modification
				|| docInstanceCode == 110		//Order: Order Adding Child(ren) and Modification
				|| docInstanceCode == 172) {	//Order: Order Adding Child(ren) and Modification-FormCEJ-Order-Bibb
			documentOrder = true;
			doc.setOrderedDoc(true);				
		} else {
			documentOrder = false;
			doc.setOrderedDoc(false);
		}
		return documentOrder;
	}

	public boolean isDocumentSignedForJudge(Documents doc, Person person) {
		boolean documentSigned = false;
		boolean ordered = this.isDocumentOrderForJudge(doc);

		List<Signatures> docSignatures = doc.getSignatures();
		if (ordered) {
			for (Signatures s : docSignatures) {
				Person personSigned = s.getSignedByPerson();
				LOG.debug("Signed Person Uuid "
						+ personSigned.getUuid());
				LOG.debug("Parameter passes Person Uuid "
						+ person.getUuid());
				if (personSigned.getUuid().equals(person.getUuid())) {
					if (s.getSignatureValue() != null) {
						documentSigned = true;
						//doc.setSignedDoc(true);
						//doc.setOrderedDoc(false);
						break;
					}
				}
			}
		}else if ((ordered) && (doc.getStatus().getCode() == 2)) {
			documentSigned = true;
			//doc.setSignedDoc(true);
		}
		return documentSigned;
	}

	public boolean isRenderRejectButton() {
		return renderRejectButton;
	}
	public void setRenderRejectButton(boolean renderRejectButton) {
		this.renderRejectButton = renderRejectButton;
	}
	public boolean isDocNoContentsMessage() {
		return docNoContentsMessage;
	}
	public void setDocNoContentsMessage(boolean docNoContentsMessage) {
		this.docNoContentsMessage = docNoContentsMessage;
	}
	public boolean isSignatureFailed() {
		return signatureFailed;
	}
	public void setSignatureFailed(boolean signatureFailed) {
		this.signatureFailed = signatureFailed;
	}
	public boolean isSignatureFailedMessage() {
		return signatureFailedMessage;
	}
	public void setSignatureFailedMessage(boolean signatureFailedMessage) {
		this.signatureFailedMessage = signatureFailedMessage;
	}
	
	/**
	 * This block enables the agent to also sign a document
	 */
	
	
	public boolean isDocumentOrderForAgent(Documents doc) {

		boolean documentOrder = false;

		int docInstanceCode = doc.getDocumentInstance().getCode();

		if (docInstanceCode == 820036 || docInstanceCode == 1820036
				|| docInstanceCode == 21820036 || docInstanceCode == 31820036
				|| docInstanceCode == 51820036) // Agency Recommendation
		{
			documentOrder = true;
		} else {
			documentOrder = false;

		}
		
		if(documentOrder == false) {
			documentOrder = doc.getDocumentInstance().isRequiresAgentSignature();
		}

		return documentOrder;
	}
	
	
	public boolean isDocumentSignedByAgent(Documents doc, Person person) {

		boolean documentSigned = false;
		boolean ordered = this.isDocumentOrderForAgent(doc);

		List<Signatures> docSignatures = new ArrayList<Signatures>();
		docSignatures = doc.getSignatures();
		if ((ordered) && (doc.getStatus().getCode() != 2)) {
			for (Signatures s : docSignatures) {
				Person personSigned = s.getSignedByPerson();
				if (personSigned.getUuid().equals(person.getUuid())) {
					if (s.getSignatureValue() != null) {
						documentSigned = true;
						// doc.setSignedDoc(true);
						// doc.setOrderedDoc(false);
						break;
					}
				}
			}
		} else if ((ordered) && (doc.getStatus().getCode() == 2)) {
			documentSigned = true;
			// doc.setSignedDoc(true);
		}
						

		return documentSigned;

	}
}
